package xinlian

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"

	"github.com/rs/zerolog/log"
)

// Client 云片sms客户端
type Client struct {
	account  string
	password string
}

// NewClient creates a new yunpian sms client.
func NewClient(account, password string) Client {
	return Client{
		account:  account,
		password: fmt.Sprintf("%x", md5.Sum([]byte(password))),
	}
}

// SendSingle sends the content to sigle mobile.
func (c Client) SendSingle(mobile, content string) error {
	param := make(url.Values)
	param["action"] = []string{"send"}
	param["verifymethod"] = []string{"pwd"}
	param["loginid"] = []string{c.account}
	param["loginpwd"] = []string{c.password}
	param["mobiles"] = []string{mobile}
	param["content"] = []string{content}

	res, err := http.PostForm("http://s.minicall.cn/2016/interface/sms.php", param)
	if err != nil {
		log.Error().Err(err).Msg("xinlian code send err")
		return ErrInteralError
	}
	defer res.Body.Close()

	decoder := json.NewDecoder(res.Body)
	var r Response
	if err = decoder.Decode(&r); err != nil {
		log.Error().Err(err).Msg("xinlian code send response resolve err")
		return ErrInteralError
	}
	if r.Code != 0 {
		return errors.New(r.Msg)
	}

	return nil
}
